package com.fhao.forum.controller;

import com.fhao.forum.common.AppResult;
import com.fhao.forum.common.ResultCode;
import com.fhao.forum.config.AppConfig;
import com.fhao.forum.model.User;
import com.fhao.forum.services.IUserService;
import com.fhao.forum.utils.MD5Util;
import com.fhao.forum.utils.StringUtil;
import com.fhao.forum.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@ApiResponses //api自动测试接口,网址在课件上
@Slf4j
@RestController //这是一个返回数据的 Controller, 同时也会把类交给spring管理
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    /**
     * 用户注册
     * @param username
     * @param nickname
     * @param password
     * @param passwordRepeat
     * @return
     */
    @ApiResponse(description = "用户注册")
    @PostMapping("/register")   //↓ @RequestParam 注解中的username表示 url 用的参数.
    public AppResult register (@RequestParam("username") @NonNull String username,
                               @RequestParam("nickname") @NonNull String nickname,
                               @RequestParam("password") @NonNull String password,
                               @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
//        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname)
//                || StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat)) {
//            //返回错误信息
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }
        //校验密码和重复密码是否相同
        if(!password.equals(passwordRepeat)) {
            //打印日志
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //处理密码
        //1.生成盐
        String salt = UUIDUtil.UUID_32();
        //2.生成密文
        String encryptPassword = MD5Util.md5Salt(password,salt);
        //3.设置密码和盐
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        //调用service层
        userService.createNormalUser(user);
        return AppResult.success();
    }

    @ApiResponse(description = "用户登录")
    @PostMapping("/login")
    public AppResult login (HttpServletRequest request,
                            @RequestParam("username") @NonNull String username,
                            @RequestParam("password") @NonNull String password) {
        //通过userService拿到用户信息
        User user = userService.login(username, password);
        //对用户信息进行非空校验, 其实在 service中我们已经进行了非空校验, 此处可以不用,但是为了保险起见,还是多校验一次
        if(user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //把user对象设置到 Session作用域中
        HttpSession session = request.getSession(true);//没有开启 session的话一定要开启session.
        session.setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success();
    }

    @ApiResponse(description = "获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,//↓表示id是非必传项
                                       @RequestParam(value = "id",required = false) Long id) {
        User user = null;
        //根据 id 的情况来执行不同的获取方式
        if(id == null) {
            //没有传 id, 从session中获取用户信息
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else {
            //从数据库中查询 用户
            user = userService.selectById(id);
        }
        if(user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @ApiResponse(description = "退出登录")
    @GetMapping("/logout")
    public AppResult logout (HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session != null) {
            //打印日志
            log.info("退出登录");
            //session不为空,用户还在登录状态,直接销毁session即可.
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    /**
     * 修改个人信息
     * @param username 用户名
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话号
     * @param remark 个人简介
     * @return
     */
    @ApiResponse(description = "修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @RequestParam(value = "username",required = false) String username,
                                @RequestParam(value = "nickname",required = false) String nickname,
                                @RequestParam(value = "gender",required = false) Byte gender,
                                @RequestParam(value = "email",required = false) String email,
                                @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @RequestParam(value = "remark",required = false) String remark) {
        //1. 不能全部为空
        if(StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
            return AppResult.failed("请输入要修改的内容");
        }
        //从session中获取id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //2. 创建一个更新对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setEmail(email);
        updateUser.setGender(gender);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        //3. 调用service
        userService.modifyInfo(updateUser);
        //4. 查询最新的用户信息
        user = userService.selectById(user.getId());
        //5. 把修改好的user放到session当中
        session.setAttribute(AppConfig.USER_SESSION,user);
        //6. 返回结果
        return AppResult.success(user);
    }

    @ApiResponse(description = "修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @RequestParam("newPassword") @NonNull String newPassword,
                                    @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {

        //1. 判断两次输入密码是否一致
        if(!newPassword.equals(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //2. 拿到当前登录用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user == null || user.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //3. 调用Service
        userService.modifyPassword(user.getId(),oldPassword,newPassword);
        //4. 强制让session失效
        if(session != null) {
            session.invalidate();
        }
        //5. 返回结果
        return AppResult.success("修改密码成功,请重新登录");
    }
}



















